import React, { useEffect, useState } from 'react';
import {
  message,
  Radio,
  Select,
  Checkbox,
  Table,
  Tag,
  Space,
  Form,
  Input,
  Button,
  Cascader,
  DatePicker,
  Drawer,
} from 'antd';
import { SettingFilled, EyeOutlined, LoadingOutlined } from '@ant-design/icons';
import {
  addUserAPI,
  getDeptsAPI,
  getUsersAPI,
  modiUserAPI,
} from '../../../apis/user/userAPI';
import styles from '@/assets/css/User.less';
import {
  addCharactersAPI,
  getCharactersAPI,
  getMenuByRoleAPI,
} from '../../../apis/character/character';
import TreeDrawer from '../../../components/character/treeDrawer';
import ModifyRole from '@/components/character/modifyRole';
import { getMenuApi } from '../../../apis/menu/menuAPI';
const { RangePicker } = DatePicker;
const { Option } = Select;

const layout = {
  labelCol: {
    span: 8,
  },
  wrapperCol: {
    span: 16,
  },
};

export default function User() {
  //获取角色对应菜单
  const getMenuByRole = async (role) => {
    // console.log('theRole', theRole);
    const res = await getMenuByRoleAPI(role.roleId);
    console.log('getMenuByRole', res);
    return res.data;
  };
  //获取所有菜单数据
  const getAllMenus = async () => {
    const res = await getMenuApi();
    console.log('getAllMenus', res);
    setAllMenus(res.data.rows.children);
  };
  const addRole = async (role) => {
    const res = await addCharactersAPI(role);
    console.log('addRole', res);
    if (res.status == 200) {
      message.success('新增成功');
      setShowDrawer(false);
    }
  };
  const getUsers = async (params) => {
    const res = await getUsersAPI({ ...params, ...pageInfo, ...searchInfo });
    console.log('getUsers', res);
    setUsersData(res.data.rows);
    setPageInfo({ ...pageInfo, total: res.data.rows.length });
  };

  const getRoles = async (params) => {
    const res = await getCharactersAPI({
      ...params,
      ...pageInfo,
      ...searchInfo,
    });
    console.log('getRoles', res);
    setRolesData(res.data.rows);
  };
  const pagChange = async (pageNum, pageSize) => {
    setPageInfo({ ...pageInfo, pageNum, pageSize });
    getUsers();
  };

  const searchFunc = async (values) => {
    // console.log('Success:', values);
    const { username } = values;
    setSearchInfo({ ...searchInfo, username });
    await getRoles();
  };

  const onFinishFailed = (errorInfo) => {
    console.log('Failed:', errorInfo);
  };

  const showModi = async (role, drawerType) => {
    setTreeLoading({ id: role.roleId, drawerType });
    const menuId = await getMenuByRole(role);

    setTheRole({ ...role, menuId, drawerType });
    setTreeLoading({});
  };

  const modiRoleAsync = async (role) => {
    const res = await modiUserAPI(role);
    console.log('modiRoleAsync', res);
    if (res.status == 200) {
      message.success('修改成功');
      setTheRole(null);
    }
  };

  const createDeptArr = (arr, id) => {
    for (let i = 0; i < arr.length; i++) {
      const dp = arr[i];
      if (dp.id == id) {
        return [id];
      } else {
        if (dp.children) {
          const childReturn = createDeptArr(dp.children, id);
          const insert = childReturn == undefined ? [undefined] : [childReturn];
          let res = [dp.id, ...insert];
          if (!res.includes(undefined)) {
            console.log(res);
            return res;
          }
        }
      }
    }
  };
  //state部分
  const [modiForm] = Form.useForm();
  const [usersData, setUsersData] = useState([]);
  let [pageInfo, setPageInfo] = useState({ pageNum: 1, pageSize: 1, total: 0 });
  let [searchInfo, setSearchInfo] = useState({});
  let [deptsData, setDeptsData] = useState([]);
  let [rolesData, setRolesData] = useState([]);
  let [showDrawer, setShowDrawer] = useState(false);
  let [addUserObj, setAddUserObj] = useState({});
  let [modiDrawer, setModiDrawer] = useState(false);
  let [modiUser, setModiUser] = useState({});
  let [allMenus, setAllMenus] = useState([]);
  let [theRole, setTheRole] = useState(null);
  let [treeLoading, setTreeLoading] = useState({});
  //effect部分
  // 挂载后
  useEffect(() => {
    getRoles();
    getAllMenus();
  }, []);
  useEffect(() => {
    console.log(theRole);
  }, [theRole]);
  let pagination = {
    total: pageInfo.total,
    showTotal: (total, range) => `${range[0]}-${range[1]} 条，共 ${total} 条`,
    showSizeChanger: true,
    pageSizeOptions: [1, 2, 3, 4, 5],
    defaultPageSize: 3,
    defaultCurrent: 1,
    onchange: pagChange,
  };
  const columns = [
    {
      title: '角色',
      dataIndex: 'roleName',
      key: 'roleName',
    },
    {
      title: '描述',
      dataIndex: 'remark',
      key: 'remark',
    },

    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
    },
    {
      title: '修改时间',
      dataIndex: 'modifyTime',
      key: 'modifyTime',
    },
    {
      title: '操作',
      key: 'userId',
      render: (data) => (
        <Space size="middle">
          {treeLoading.drawerType == 'modify' &&
          treeLoading.id == data.roleId ? (
            <LoadingOutlined />
          ) : (
            <SettingFilled
              style={{ color: '#5eaaf6' }}
              onClick={() => showModi(data, 'modify')}
            ></SettingFilled>
          )}
          {treeLoading.drawerType == 'view' && treeLoading.id == data.roleId ? (
            <LoadingOutlined />
          ) : (
            <EyeOutlined
              onClick={() => showModi(data, 'view')}
              style={{ color: '#5ac293' }}
            ></EyeOutlined>
          )}
        </Space>
      ),
    },
  ];
  const rowSec = {
    type: 'checkbox',
  };
  return (
    <div style={{ width: '100%' }}>
      角色管理
      <div className={styles.userHead}>
        {/* 搜索栏 */}
        <Form
          name="basic"
          {...layout}
          layout="inline"
          onFinish={searchFunc}
          onFinishFailed={onFinishFailed}
          autoComplete="off"
        >
          <Form.Item label="角色" name="roleName">
            <Input />
          </Form.Item>

          <Form.Item label="创建日期" name="createTime">
            <RangePicker
              onChange={(_, dates) => {
                const [createTimeFrom, createTimeTo] = dates;
                setSearchInfo({ ...searchInfo, createTimeFrom, createTimeTo });
              }}
            />
          </Form.Item>
          <Form.Item
            wrapperCol={{
              offset: 8,
              span: 16,
            }}
          >
            <Button type="primary" htmlType="submit">
              搜索
            </Button>
          </Form.Item>
        </Form>
      </div>
      <div className={styles.opers}>
        <Button
          type="primary"
          onClick={() => {
            setShowDrawer(true);
          }}
        >
          新增
        </Button>
      </div>
      <Table
        pagination={pagination}
        dataSource={rolesData}
        columns={columns}
        rowSelection={rowSec}
        className={styles.userTable}
      />
      <TreeDrawer
        addRole={addRole}
        setTheRole={setTheRole}
        allMenus={allMenus}
        showDrawer={showDrawer}
        setShowDrawer={setShowDrawer}
      ></TreeDrawer>
      <ModifyRole
        modiRoleAsync={modiRoleAsync}
        theRole={theRole}
        setTheRole={setTheRole}
        allMenus={allMenus}
      ></ModifyRole>
    </div>
  );
}
